import html2pdf from 'html2pdf.js';
import dayjs from 'dayjs';
// PDF生成模板
export const generateReportTemplate = (params) => {
  const { record, user, bloodData, probability, imgData, text, date } = params;
  const container = document.createElement('div');
  container.className = 'pdf-container';
  const bloodIndicatorMap = {
    'RBC': { label: 'RBC', unit: 'T/L' },
    'HGB': { label: 'HGB', unit: 'g/L' },
    'HCT': { label: 'HCT', unit: '%', formatter: v => (v * 100).toFixed(1) },
    'MCH': { label: 'MCH', unit: 'pg' },
    'MCHC': { label: 'MCHC', unit: 'g/L' },
    'MCV': { label: 'MCV', unit: 'fL' },
    'RDW-SD': { label: 'RDW-SD', unit: 'fL' }
  };
  container.innerHTML = `
    <style>
      .pdf-title { 
        text-align: center; 
        margin: 5px 0; /* 减少上下边距 */
        font-size: 26px; /* 调整字体大小 */
        font-family: 'SimSun', sans-serif;
      }
      p {
        font-family: 'SimSun', sans-serif;
        margin: 0;
        padding: 0;
      }
    
      

      .indicator-grid {
        display: grid;
        grid-template-columns: repeat(3, 1fr); /* 分为3列 */
        gap: 12px;
      }

      .indicator-item {
        break-inside: avoid;
        min-width: 220px;
        text-align: left;
      }

      .subsection-title {
        font-size: 18px;
        color: black;
        margin:0;
        text-align: left;
      }

      .cell-analysis-container {
        display: flex;
        margin-top: 10px;
        height: 320px;
      }

      .cell-images {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 5px;
      }
      .section {
        margin: 10px auto; 
        width: 95%;
      }
      .cell-image-item {
        flex: 1;
        min-width: 150px;
        max-width: 150px;
      }

      .image-placeholder {
        width: 100%;
        height: 105px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 0;
        margin: 0; 
  text-align: center;
      }
  .image-placeholder p {
  margin: 0; 
  font-size: 12px; 
}

      .cell-data-table {
        flex: 2;
        min-width: 400px;
      }

      table {
        width: 95%;
        border-collapse: collapse;
      }

      table th, table td {
        border: 1px solid #0a9595;
        padding: 3px;
        text-align: center;
        font-family: 'SimSun', sans-serif;
      }

      table th {
        font-size: 12px;
        background-color: #f8f8f8;
      }

      .cell-type-details {
        display: flex;
        flex-direction: column;
        gap: 5px;
      }

      .cell-type-card {
        border: 1px solid #0a9595;
        border-radius: 5px;
        padding: 3px;
        background-color: white;
      }

      .cell-detail-text {
        font-size: 12px;
        line-height: 1.2;
        margin: 0;
        padding: 2px 0;
      }

      .probability-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
        gap: 10px;
        margin-top: 10px;
      }

      .probability-item {
        padding: 8px;
        border-radius: 4px;
        text-align: center;
      }

      .footer-line {
        margin: 8px auto; 
        border-top: 1px solid #666;
        width: 95%;
      }

      .footer-info {
        right: 30px;
        bottom: 20px;
        text-align: right;
        font-size: 12px;
        line-height: 1.5;
      }

      .pdf-container {
        position: relative;
        padding-bottom: 5px;
      }
    </style>

    <h2 class="pdf-title">地中海贫血筛查报告</h2>
      <p class="pdf-title">${user.departmentName}</p>
    <div class="patient-info">
    <div class="footer-line"></div>
     <div class="section">
  <h class="subsection-title">患者信息</h>
  <div class="indicator-grid">
    <p class="indicator-item">姓名：${record.name}</p>
    <p class="indicator-item">性别：${record.sex}</p>
    <p class="indicator-item">年龄：${record.age}</p>
    <p class="indicator-item">就诊卡号：${record.visitCardId}</p>
    <p class="indicator-item">电话号码：${record.phone}</p>
  </div>
    </div>
</div>
<div class="footer-line"></div>
    <div class="section">
      <h class="subsection-title">血常规指标</h>
      <div class="indicator-grid">
    ${Object.entries(bloodData).map(([key, val]) => {
    const indicator = bloodIndicatorMap[key] || { label: key, unit: '' };
    const value = indicator.formatter ? indicator.formatter(val) : val;
    return `<p class="indicator-item">${indicator.label}：${value} ${indicator.unit}</p>`;
  }).join('')}
  </div>
    </div>
    <div class="footer-line"></div>
    <div class="section" style="margin-top: 10px;">
  <h class="subsection-title">细胞分析</h>
  <div class="cell-analysis-container">
    <div class="cell-images">
      ${imgData.map((item, index) => `
        <div class="cell-image-item">
          <div class="image-placeholder">
   <img src="${item.originalImageUrl}?t=${new Date().getTime()}" style="max-width:90%; height:auto;"/>
 <p>${index + 1}</p>
</div>
        </div>
      `).join('')}
    </div>
    <div class="cell-data-table">
      <table>
        <thead>
          <tr>
            <th>图片</th>
            <th>细胞总数</th>
            <th>正常细胞</th>
            <th>棘红细胞</th>
            <th>椭圆形红细胞</th>
          </tr>
        </thead>
        <tbody>
          ${imgData.map((item, index) => `
            <tr>
              <td>${index + 1}</td>
              <td>${item.total}</td>
              <td>
                <div class="cell-type-details">
                  ${item.details.map(d => `
                    ${d.type === '正常细胞' ? `${d.quantity}/${(d.percentage * 100).toFixed(1)}%` : ''}
                  `).join('')}
                </div>
              </td>
              <td>
                <div class="cell-type-details">
                  ${item.details.map(d => `
                    ${d.type === '棘红细胞' ? `${d.quantity}/${(d.percentage * 100).toFixed(1)}%` : ''}
                  `).join('')}
                </div>
              </td>
              <td>
                <div class="cell-type-details">
                  ${item.details.map(d => `
                    ${d.type === '椭圆形红细胞' ? `${d.quantity}/${(d.percentage * 100).toFixed(1)}%` : ''}
                  `).join('')}
                </div>
              </td>
            </tr>
          `).join('')}
        </tbody>
      </table>
    </div>
  </div>
</div>
<div class="footer-line"></div>
 <div class="section">
  <h class="subsection-title">系统预测概率</h>
  <div class="probability-grid">
    ${Object.entries(probability).map(([type, value]) => `
      <div class="probability-item">
        <p>${type}：${(value * 100).toFixed(3)}%</p>
      </div>
    `).join('')}
  </div>
</div>
<div class="footer-line"></div>
 <div class="section">
  <h class="subsection-title">备注</h>
  <p style="height: 110px; overflow-y: auto;">${text}</p>
</div>
<div class="footer-line"></div>
    <div class="footer-info">
<p>创建人：${user.name} ${user.identity}</p>
<p>创建时间：${date}</p>
 </div>
  `;

  return container;
};

// PDF生成器
export const generatePDF = async (element, filename) => {
  const options = {
    margin: 10,
    filename: `${filename}_报告_${dayjs().format('YYYYMMDD')}.pdf`,
    html2canvas: {
      scale: 2,
      logging: true,
      useCORS: true,
      async: true,
      allowTaint: true
    },
    jsPDF: {
      unit: 'mm',
      format: 'a4',
      orientation: 'portrait'
    }
  };

  try {
    // 生成PDF
    const pdfBlobUrl = await html2pdf().set(options).from(element).output('bloburl');
    // 自动下载PDF文件
    await html2pdf().set(options).from(element).save();
    // 返回PDF文件的URL
    return pdfBlobUrl;
  } catch (error) {
    console.error('PDF生成失败:', error);
    throw new Error('PDF生成失败');
  }
};